package engine.game.level.tiles;

import java.util.ArrayList;
import java.util.List;

import engine.game.Tickable;
import engine.game.gfx.ColoredSprite;

public class AnimatedTile extends Tile implements Tickable {

    private long lastStateChange;
    private List<ColoredSprite> sprites = new ArrayList<>();

    private int currentSpriteIndex;

    public AnimatedTile(String name, List<ColoredSprite> sprites, boolean isSolid) {
        super(name, isSolid);

        this.sprites = sprites;

        currentSpriteIndex = 0;
        sprite = sprites.get(currentSpriteIndex);
        lastStateChange = System.currentTimeMillis();

        Tile.addTile(this);
    }

    @Override
    public ColoredSprite staticSprite() {
        return this.sprites.get(0);
    }

    @Override
    public void tick() {
        long now = System.currentTimeMillis();
        double delta = (now - lastStateChange) / 1E3;

        if (delta > 1) {
            incrementState();
            lastStateChange = now;
        }
    }

    private void incrementState() {
        currentSpriteIndex++;
        while (currentSpriteIndex >= sprites.size()) {
            currentSpriteIndex -= sprites.size();
        }
        sprite = sprites.get(currentSpriteIndex);
    }

}
